﻿using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Formatting;
using System.Globalization;
using Serilog.Expressions.Compilation.Linq;
using System.Diagnostics;
using Microsoft.Extensions.Logging;

namespace Cngot.Extensions.Logger
{
    public class TraceRenderedCompactJsonFormatter : ITextFormatter
    {
        readonly JsonValueFormatter _valueFormatter;

        /// <summary>
        /// Construct a <see cref="CompactJsonFormatter"/>, optionally supplying a formatter for
        /// <see cref="LogEventPropertyValue"/>s on the event.
        /// </summary>
        /// <param name="valueFormatter">A value formatter, or null.</param>
        public TraceRenderedCompactJsonFormatter(JsonValueFormatter valueFormatter = null)
        {
            _valueFormatter = valueFormatter ?? new JsonValueFormatter(typeTagName: "$type");
        }

        /// <summary>
        /// Format the log event into the output. Subsequent events will be newline-delimited.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        public void Format(LogEvent logEvent, TextWriter output)
        {
            FormatEvent(logEvent, output, _valueFormatter);
            output.WriteLine();
        }

        /// <summary>
        /// Format the log event into the output.
        /// </summary>
        /// <param name="logEvent">The event to format.</param>
        /// <param name="output">The output.</param>
        /// <param name="valueFormatter">A value formatter for <see cref="LogEventPropertyValue"/>s on the event.</param>
        public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFormatter valueFormatter)
        {
            if (logEvent == null) throw new ArgumentNullException(nameof(logEvent));
            if (output == null) throw new ArgumentNullException(nameof(output));
            if (valueFormatter == null) throw new ArgumentNullException(nameof(valueFormatter));

            output.Write("{\"ResponseTime\":\"" + logEvent.Timestamp.LocalDateTime.ToString("O") + "\"");
            if (!logEvent.Properties.ContainsKey("ResponseBody"))
            {
                output.Write(",\"ResponseBody\":");
                var message = logEvent.MessageTemplate.Render(logEvent.Properties, CultureInfo.InvariantCulture);
                JsonValueFormatter.WriteQuotedJsonString(message, output);
            }
            //output.Write(",\"@i\":\"");
            //var id = EventIdHash.Compute(logEvent.MessageTemplate.Text);
            //output.Write(id.ToString("x8", CultureInfo.InvariantCulture));
            //output.Write('"');

            //// if (logEvent.Level != LogEventLevel.Information)
            //{
            //    output.Write(",\"@l\":\"");
            //    output.Write(logEvent.Level);
            //    output.Write('\"');
            //}


            output.Write(",\"Level\":\"");
            if (logEvent.Level == LogEventLevel.Verbose || (logEvent.Level == LogEventLevel.Information && logEvent.Properties.Any(q => q.Key == "SourceContext" && q.Value?.ToString().Replace("\"", "") == "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware")))
            {
                output.Write(LogLevel.Trace);
            }
            else
            {
                output.Write(logEvent.Level);
            }
            output.Write('\"');

            if (logEvent.Exception != null)
            {
                output.Write(",\"Exception\":");
                JsonValueFormatter.WriteQuotedJsonString(logEvent.Exception.ToString(), output);
            }

            foreach (var property in logEvent.Properties)
            {
                if (property.Key != "HttpLog" && property.Key != "EventId")
                {
                    var name = property.Key;
                    if (name.Length > 0 && name[0] == '@')
                    {
                        // Escape first '@' by doubling
                        name = '@' + name;
                    }

                    output.Write(',');
                    JsonValueFormatter.WriteQuotedJsonString(name, output);
                    output.Write(':');
                    valueFormatter.Format(property.Value, output);
                }
            }

            output.Write('}');
        }
    }
}
